//
//  BIZContractDetailVC.m
//  ConsultantVersion
//
//  Created by 小龙 on 2017/4/18.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "BIZContractDetailVC.h"
#import "FileOperation.h"
#import "BIAppraiseViewController.h"

@interface BIZContractDetailVC ()
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *companyNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *requireLabel;
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;

@property (weak, nonatomic) IBOutlet UILabel *contractNameLabel;
@property (weak, nonatomic) IBOutlet UIButton *downLoadBtn;
@property (weak, nonatomic) IBOutlet UIButton *uploadBtn;
@property (weak, nonatomic) IBOutlet UIButton *reciveBtn;

@property (weak, nonatomic) IBOutlet UIButton *refuseBtn;

@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (weak, nonatomic) IBOutlet UILabel *passBackLabel;
@property (weak, nonatomic) IBOutlet UIButton *passBackBtn;

@property (weak, nonatomic) IBOutlet UIButton *reciveContractBtn;
@property (weak, nonatomic) IBOutlet UIButton *refuseContractBtn;

@property (weak, nonatomic) IBOutlet UIView *labelbackView;

@property (weak, nonatomic) IBOutlet UILabel *posiationLabel;


/** <#strong属性注释#> */
@property (nonatomic, strong) BIZContractModel *contractModel;


@end

@implementation BIZContractDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"合同";
    
    [self getContractDetailData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.isPush) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kReloadContractListNotification object:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getContractDetailData
{
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kContractDetail parameters:@{@"uuid":self.uuid} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"%@",responseObject);
        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 1) {
            self.contractModel = [BIZContractModel yy_modelWithJSON:responseObject[@"data"]];
            
            
            if ([self.contractModel.redType integerValue] == 1) {
                if (self.didClickReturnBlock) {
                    self.didClickReturnBlock();
                }
            }
            [self setupUI];
        } else {
            [MBProgressHUD showErrorMessage:responseObject[@"des"]];
            if ([responseObject[@"code"] integerValue]== 2) {
                BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                MPWeakSelf(self);
                vc.loginSuccessBlock = ^(){
                    [weakself getContractDetailData];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"%@",error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
}

- (void)setupUI
{
    [SDWebImageTool imageView:self.headImageView imageName:self.contractModel.headImg placeHolder:@"default-head" showProgress:NO];
    self.nameLabel.text = self.contractModel.cname;
    self.companyNameLabel.text = self.contractModel.fname;
    self.requireLabel.text = self.contractModel.content;
    self.dateLabel.text = [NSDate stringFromTimestamp:self.contractModel.comTime];
    self.posiationLabel.text = self.contractModel.position;
    
    /** 状态：状态: 0 初始 未接单 1 接单 2 拒单 3 已回传 4服务完成 5过期 */
    self.passBackBtn.hidden = YES;
    switch ([self.contractModel.status integerValue]) {
            case 0:
        {
            self.statusLabel.text = @"咨询师未接单";
            self.statusLabel.textColor = HEXCOLOR(0xfb6a31);
            self.labelbackView.hidden = YES;
            self.reciveBtn.hidden = YES;
            self.refuseBtn.hidden = YES;
            
        }
            break;
            case 1:
        {
            self.statusLabel.text = @"咨询师已接单";
            self.statusLabel.textColor = HEXCOLOR(0x00c44e);
            self.labelbackView.hidden = YES;
            self.reciveBtn.hidden = YES;
            self.refuseBtn.hidden = YES;
        }
            break;
            
            case 2:
        {
            self.statusLabel.text = @"咨询师已拒单";
            self.statusLabel.textColor = HEXCOLOR(0x2079EF);
            self.labelbackView.hidden = YES;
            self.reciveBtn.hidden = YES;
            self.refuseBtn.hidden = YES;
        }
            break;
            
            case 3:
        {
            self.statusLabel.text = @"咨询师已回传合同";
            self.statusLabel.textColor = HEXCOLOR(0x00c44e);
            self.passBackLabel.text = @"咨询师已回传合同";
            self.contractNameLabel.text = self.contractModel.cuserFileName;
            self.labelbackView.hidden = NO;
            self.passBackBtn.hidden = YES;
            self.reciveBtn.hidden = NO;
            [self.reciveBtn setTitle:@"确认完成服务" forState:UIControlStateNormal];
            self.refuseBtn.hidden = YES;
        }
            break;
            
            case 4:
        {
            self.statusLabel.text = @"服务完成";
            self.statusLabel.textColor = HEXCOLOR(0xffa200);
            self.labelbackView.hidden = YES;
            self.reciveBtn.hidden = YES;
            self.refuseBtn.hidden = YES;
        }
            break;
            
            case 5:
        {
            self.statusLabel.text = @"过期";
            self.statusLabel.textColor = HEXCOLOR(0xfb6a31);
            self.labelbackView.hidden = YES;
            self.reciveBtn.hidden = YES;
            self.refuseBtn.hidden = YES;
        }
            break;
            
        default:
        {
            self.statusLabel.text = @"服务无响应";
            self.statusLabel.textColor = HEXCOLOR(0xcc100f);
            self.labelbackView.hidden = YES;
            self.reciveBtn.hidden = YES;
            self.refuseBtn.hidden = YES;
        }
            break;
    }
    
}

- (IBAction)downLoadBtnClick {
    
    NSString *url = [NSString stringWithFormat:@"%@%@" ,kDownloadUrl ,self.contractModel.cuserFile];
    [RequestTool downLoadFile:url progress:^(NSProgress * _Nonnull downloadProgress) {
        DeLog(@"downloadProgress++++:%f",1.0 *downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD showProgressWithMessage:@"下载中" progress:1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount];
        });
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        DeLog(@"destination++++++:%@", response);
        NSString *documentPath = [FileOperation getDocumentsPath];
        NSString *docPath = [documentPath  stringByAppendingPathComponent:self.contractModel.cuserFileName];
        
        NSString *tempStr = [docPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        DeLog(@"docPath:%@",docPath);
        DeLog(@"docPath:%@",tempStr);

        return [NSURL fileURLWithPath:docPath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nonnull filePath, NSError * _Nonnull error) {
        DeLog(@"completionHandler++++++:%@", response);
        DeLog(@"error++++++:%@", error);
        NSLog(@"%@",filePath);
        DeLog(@"[filePath absoluteString]:%@",[filePath absoluteString]);
        if (!error) {
            [MBProgressHUD showSuccessMessage:@"下载完成"];
        }
        else {
            if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
            }
            else {
                [MBProgressHUD showErrorMessage:@"服务器繁忙"];
            }
        }
    }];
    
}

- (IBAction)uploadBtnClick {
//    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    [MBProgressHUD showAnimationHUD];
//    [RequestTool POST:kUploadUrl parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        DeLog(@"responseObject+++++:%@",responseObject);
//        [MBProgressHUD  hideHUD];
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        DeLog(@"error+++++:%@",error);
//        if [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
//            [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
//        }
//        else {
//            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
//        }
//    }];
}

- (IBAction)reciveBtnClick {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"咨询师是否已经完成服务?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confim = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self clickFinshService];
    }];
    [alert addAction:confim];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:cancel];
    
    
    [self presentViewController:alert animated:YES completion:nil];

}

- (void)clickFinshService
{
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kServiceCompeleteUrl parameters:@{@"uuid":self.contractModel.uuid} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"responseObject+++++:%@",responseObject);
        [MBProgressHUD  hideHUD];
        if ([responseObject[@"code"] integerValue] == 1) {
            
            if (self.isPush) {
                [[NSNotificationCenter defaultCenter] postNotificationName:kReloadContractListNotification object:nil];
            }
            if (self.compeleteServiceReturnBlock) {
                self.compeleteServiceReturnBlock();
            }

            [self addChildViewController:[BIAppraiseViewController showWithURL:kContractAndOfflineEvaluationUrl uuid:self.uuid type:@"1" finishBlock:^{
                [self.navigationController popViewControllerAnimated:YES];
            }]];
        }else {
            [MBProgressHUD showErrorMessage:responseObject[@"des"]];
            if ([responseObject[@"des"] integerValue] == 2) {
                BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error+++++:%@",error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
}


- (IBAction)refuseBtnClick {
    
//    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
//    [MBProgressHUD showAnimationHUD];
//    [RequestTool POST:kRefuseOrderUrl parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        DeLog(@"responseObject+++++:%@",responseObject);
//        [MBProgressHUD  hideHUD];
//        //        BIZContractListModel *model = [BIZContractListModel yy_modelWithJSON:responseObject];
//        //        if ([model.code integerValue] == 1) {
//        //            [self.contractsArr addObjectsFromArray:model.contractArr];
//        //            self.lastId += model.contractArr.count;
//        //            [self.tableView reloadData];
//        //        } else {
//        //            [MBProgressHUD showErrorMessage:model.des];
//        //            if ([model.code integerValue] == 2) {
//        //                BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
//        //                MPWeakSelf(self);
//        //                vc.loginSuccess = ^(){
//        //                    [weakself getNewContractsListData];
//        //                };
//        //                [self presentViewController:vc animated:YES completion:nil];
//        //            }
//        //        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        DeLog(@"error+++++:%@",error);
//        if [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
//            [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
//        }
//        else {
//            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
//        }
//    }];
}

@end
